<?php
namespace app\common\service;

use app\common\utils\ErrorCode;
use app\common\utils\Massage;
use app\common\utils\Res;
use app\service\sys\UserBehaviorService;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use think\facade\Db;

class JwtService
{
    protected static $key = 'Mmc@Tsg#888+^2024%';
    protected static $iss = 'Mmc@Live2024';
    protected static $nbf = 3;
    protected static $exp = 86400*7; //设置过期时间(单位秒)为7天

    public static function createToken($data, $table=null)
    {
        $iatTime = time();
        $nbfTime = $iatTime + self::$nbf;
        $expireTime = $iatTime + self::$exp;
        $token = [
            "iss" => self::$iss, // 发行者
            "aud" => '', // 接收者
            "iat" => $iatTime, // 发行时间
            "nbf" => $nbfTime, // 生效时间
            "exp" => $expireTime, // 过期时间
            "data" => $data
        ];
        $jwt = JWT::encode($token, self::$key);
        UserBehaviorService::logCreateToken($jwt, $token, $expireTime, $data, $table);
        return $jwt;
    }

    public static function checkToken($token)
    {
        //$sysJwt = Db::table('xh_sys_jwt')->where('token', $token)->find();
        //if(empty($sysJwt)) {
        //    return Res::tokenError(Massage::ROULE); //非法操作
        //}
        //if (date('Y-m-d H:i:s') > $sysJwt['expire_time']) {
        //    return Res::tokenError(Massage::TOKENNOWTIME); //签名过期
        //}
        try {
            JWT::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = JWT::decode($token,self::$key,array('HS256')); //HS256方式，这里要和签发的时候对应
            $arr = (array)$decoded;
            $arr['code'] = ErrorCode::SUCCESS;
            //UserBehaviorService::logInsert($sysJwt['id'], (array)$arr['data'], $sysJwt['table']);
            return $arr;

        } catch (SignatureInvalidException $e) {
            return Res::tokenError(Massage::TOKENERROR); //签名错误
        } catch (BeforeValidException $beforeValidException) {
            return Res::tokenError(Massage::TOKENDEFALU); //签名失效
        } catch (ExpiredException $expiredException) {
            return Res::tokenError(Massage::TOKENNOWTIME); //签名过期
        } catch (\Exception $exception) {
            return Res::error($exception->getMessage());
            //return Res::tokenError(Massage::TOKENNULL); //未知错误
        }
    }
    
}